<?php
namespace helper;
use think\facade\Db;
use think\facade\Log;
use think\facade\Env;
use app\common\model\Wechat as WechatModel;
use EasyWeChat\Factory;
// 图文回复
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
// 图片回复
use EasyWeChat\Kernel\Messages\Image;

class Wechat
{
	protected $wx_appid;
    protected $wx_appsecret;
	protected $config;
    /**
     * 构造函数
     *
     */
    public function __construct($domain='')
    {
    	$domain = $domain==''?request()->domain():$domain;
    	
        $map[] = ['domain','=',$domain];
        $map[] = ['status','=',1];
        $wxconfig = WechatModel::where($map)->find();
        if ($wxconfig) {
            $this->config = [
                'app_id' => $wxconfig['appid'],
                'secret' => $wxconfig['appsecret'],
                'token'  => $wxconfig['token'],
                'aes_key' => $wxconfig['aeskey'],
                // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
                'response_type' => 'array',
                'log' => [
                    'level' => 'debug',
                    'file' => app()->getruntimePath() . 'log/'.date('Ymd').'/wechat_debug.log',
                ],
            ];
            $this->app = Factory::officialAccount($this->config);
            $this->wx_appid = $wxconfig['appid'];
            $this->wx_appsecret = $wxconfig['appsecret'];
        }else{
            echo '微信配置错误';die;
        }
    }
	public function get_config()
    {
		return $this->config;
    }
    /**
     * 获取AccessToken
     **/
    public function getAccessToken()
	{
	    $accessToken = $this->app->access_token;
	    $token = $accessToken->getToken(); // EasyWechat已经帮我们实现了accessToken的缓存问题，我们直接拿来用就行了
	    return json($token);
	}
	// 消息事件处理器
    public function messageHandler($message){
        
    	switch ($message['MsgType']) {
            case 'event':
            	$messageEvent = $message['Event'];
                $messageKey = (isset($message['EventKey']) && !empty($message['EventKey'])) ? $message['EventKey'] : '';
                $returnInfo = $this->eventHandler($messageEvent, $messageKey);
                return $returnInfo;
                break;
            case 'text':
                $info = Db::name('wx_keys')->where('keys',$message['Content'])->find();
                $res = $this->replyMsg($info);
                return $res;
                break;
            case 'image':
                return '收到图片消息';
                break;
            case 'voice':
                return '收到语音消息';
                break;
            case 'video':
                return '收到视频消息';
                break;
            case 'location':
                return '收到坐标消息';
                break;
            case 'link':
                return '收到链接消息';
                break;
            default:
                return '收到其它消息';
                break;
        }
    }
    
    private function eventHandler($messageEvent, $eventKey)
    {
    	$messageEvent = strtolower($messageEvent);
        switch ($messageEvent) {
	        case 'subscribe': // 订阅事件
	        	
	            return '欢迎订阅';
	            break;
	        case 'unsubscribe': // 取消订阅事件
	            // TODO 可以添加日志等其他逻辑
	            return '';
	            break;
	        case 'click': // 处理菜单点击事件
	        	
	            return $this->menuClickEventHandler($eventKey);
	            break;
	        default:
	            return "{$messageEvent}, {$eventKey}";
	            break;
	    }
    }
    /**
	 * 菜单栏中type为click的按钮才会发送return的消息回去
	 * eventKey是设置菜单时type为click的key值
	 */
	private function menuClickEventHandler($eventKey)
	{
		$menuid = str_replace('key_','',$eventKey);
		$menu = Db::name('wx_menu')->where('id',$menuid)->find();
		$eventKey = $menu['menu_event'];
		
	    switch ($eventKey) {
	        case 'click':
	            	$info = Db::name('wx_keys')->where('id',$menu['keys_id'])->find();
					if (!$info) {
						return '暂无匹配';
					}
					$res = $this->replyMsg($info);
		            return $res;
	            break;
	        case 'view':
	            return '点击了二级菜单的 subMenuClick 按钮';
	            break;
	        default:
	            return "嘻嘻";
	            break;
	    }
	}
	// 回复消息
	private function replyMsg($info){
		$no_msg = '暂无匹配';
		$error_msg = '服务器故障';
		switch ($info['msgtype']) {
	        case 'text':
	            return $info['content'];
	            break;
	        case 'news':
	            try{
	        		$article_ids = Db::name('wx_news')->where('id',$info['news_id'])->value('article_id');
	                if (!$article_ids) {
	                    return $no_msg;
	                }
	                $articles = Db::name('wx_news_article')->field('id,title,description,image')->where('id','IN',$article_ids)->select();
	                if (!$articles) {
	                    return $no_msg;
	                }
	                
	                $items = [];
	                foreach ($articles as $key => $value) {
	                	// 10月12日起  被动回复消息 只能为1条
	                	if ($key > 0) {
	                		break;
	                	}
	                	$data = [
	                        'title'       => $value['title'],
	                        'description' => $value['description'],
	                        'url'         => url("@mobile/wechat.wechat/info", [], false, true) . "?id={$value['id']}",
	                        'image'       => picredirect($value['image']),
	                    ];
	                    // Log::mylog('wxmessage',$data,'message');
	                    $items[] = new NewsItem($data);
	                }
	                
	                $news = new News($items);
	                return $news;
	        	} catch (\Exception $e) {
	        		Log::mylog('wxmessage',$e->getMessage(),'message');
	        		return $error_msg;
	            }
	            break;
	    	case 'image':
	    		try{
	    			$media_id = $this->uploadMedia($info['image_url']);
		            if (empty($info['image_url']) || !$media_id) {
		            	return $error_msg;
		            }
		       		$image = new Image($media_id);
		        	return $image;
	    		} catch (\Exception $e) {
	        		Log::mylog('wxmessage',$e->getMessage(),'message');
	        		return $error_msg;
	            }
	    		
	           break;
	        default:
	            return "嘻嘻！更多功能正在开发哦！";
	            break;
	    }
	}
	/**
	 * 上传永久素材
	 */
	public function uploadMedia($image_url,$type = 'image'){
		$map = ['md5' => md5($image_url), 'appid' => $this->wx_appid];
		if (($mediaId = Db::name('wx_media')->where($map)->value('media_id'))) return $mediaId;
		$result = $this->app->material->uploadImage('./'.$image_url);
		if ($result['media_id']) {
			$data = [
				'appid' => $this->wx_appid,
				'md5' => $map['md5'],
				'type' => $type,
				'media_id' => $result['media_id'],
				'local_url' => $image_url,
				'media_url' => $result['url'],
				'create_at' => date('Y-m-d H:i:s'),
			];
			Db::name('wx_media')->insert($data);
			return $result['media_id'];
		}
		
		
	}
}